﻿var serverURL = "http://localhost:1445/NhaTroService.svc";
var getHostelURL = "http://localhost:1445/NhaTroService.svc/NhaTro";
var isSearch = 1;
var map; //map canvans
var infowindow;
//function initialize() {
//    if (navigator.geolocation)
//        navigator.geolocation.getCurrentPosition(function (pos) {
//            var myOptions = {
//                //get current location
//                center: new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude),
//                zoom: 12,
//                mapTypeId: google.maps.MapTypeId.ROADMAP
//            };
//            map = new google.maps.Map(document.getElementById("map"), myOptions);
//        }, function (error) {
//            var myOptions = {
//                //center: new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude),
//                zoom: 16,
//                mapTypeId: google.maps.MapTypeId.ROADMAP
//            };
//            map = new google.maps.Map(document.getElementById("map"), myOptions);
//        }
//        );
//}
function initialize() {
    //map.setCenter(new GLatLng(10.809300304410629, 106.61991119384766), 15);
    var latlng = new google.maps.LatLng(10.809300304410629, 106.61991119384766);
    var myOptions = {
        zoom: 13,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map"), myOptions);
	//k=0;
    //set click event
    google.maps.event.addListener(map, 'click', function (event) {
		if(isSearch==0){// Khôg phai tim kiem thi moi cho cho addMarker
			$("#latitude").val(event.latLng.lat());
			$("#longitude").val(event.latLng.lng());
			var myLatlng = new google.maps.LatLng(event.latLng.lat(),event.latLng.lng());
			var marker = new google.maps.Marker({
				position: myLatlng, 
				map: map,
				title:"Nhà trọ ở đây"
			});
			google.maps.event.addListener(marker, "click", function() {
				marker.setMap(null);
			});
		}

    });// event
	


}

//load all marker
function loadAllMarker() {
    $.ajax({
        url: "http://localhost:1445/NhaTroService.svc/NhaTro/DanhSach",
        data: "{}",
        type: "GET",
        contentType: "application/javascript", //set ajax call through cross domain
        dataType: "jsonp",
        success: function (data) {
            //loop the json array
            $.each(data, function (index) {
                //set marker
                var latLng = new google.maps.LatLng(data[index].ViDo, data[index].KinhDo); //create latitude, longtitude
                var marker = new google.maps.Marker({ //set marker to map
                    position: latLng,
                    map: map
                }); //end set marker 

                //alert(data[index].ViDo);
                //create marker event listener
                (function (marker) {
                    google.maps.event.addListener(marker, 'click', function () { //set click event

                        if (!infowindow) {
                            infowindow = new google.maps.InfoWindow();
                        }
                        //set content when I click this marker
                        infowindow.setContent(
                                'Số nhà: ' + data[index].SoNha + '<br>Chú thích : ' + data[index].ChuThich +
                                "<br/><span class=\"delete_address\" style=\"color:red;cursor:pointer\" onclick=\"deleteNhaTro(" + data[index].MaDuLieu + ")\">Xóa nhà trọ này</span><span class=\"delete_address\" style=\"color:red;cursor:pointer\" onclick=\"getNhaTroById(" + data[index].MaDuLieu + ")\">Cập nhật thông tin nhà trọ này</span>"
                            );

                        infowindow.open(map, marker);

                    });
                })(marker); //end create marker event listener

            }); //end each


        } //end success function
    });   //end ajax
}

function deleteNhaTro(id) {
    var link = "Delete.aspx";
    $.ajax({
        url: link,
        data: "id=" + id,
        type: "post",
        success: function (res) {
            if (res == "true")
                alert("Xóa thành công");
            loadMarkerOption();
        },
        error: function () {
            alert("error");
        }
    });
}
function deleteNhaTro2(idNhaTro){
	//alert(idNhaTro);
	url1 = "http://localhost:1445/NhaTroService.svc/NhaTro/Xoa/" + idNhaTro;
	alert(url1);
	$.ajax({
		url: "http://localhost:1445/NhaTroService.svc/NhaTro/Xoa/" + idNhaTro,
		type: "DELETE",
		contentType: "text/html; charset=utf-8",
		data: idNhaTro,
		success: function (msg) {
			alert('success');
		},
		error: function (msg) {
			alert(msg);
		}
	}); // end ajax 

}
function getNhaTroById(idNhaTro){
	var strHTML = '';
	$.ajax({
        url: "http://localhost:1445/NhaTroService.svc/NhaTro/DanhSach/"+ idNhaTro,
        data: "{}",
        type: "GET",
        contentType: "application/javascript", //set ajax call through cross domain
        dataType: "jsonp",
        success: function (data) {
			//$('#divInsert').hide('fast');
			//$('#divInsert').slideDown('fast');
            $.each(data, function (index) {
   			    $('#MaDuLieu').val(data[index].MaDuLieu);
				$('#MaTenDiaDiem').val(data[index].MaTenDiaDiem);
				$('#sonha').val(data[index].SoNha);
				$('#chuthich').val(data[index].ChuThich);
				//$('#mad').val(data[index].MaDuong);
				$('#mad option[value="' + data[index].MaDuong + '>"]').attr("selected", "selected");
				//$('#maph').val(data[index].MaPhuong);
				$('#maph option[value="' + data[index].MaPhuong + '>"]').attr("selected", "selected");
				//$('#maqh').val(data[index].MaQuanHuyen);
				$('#maqh option[value="' + data[index].MaQuanHuyen  + '>"]').attr("selected", "selected");
				//$('#matinhthanh').val(data[index].MaTinhThanh);
				$('#longitude').val(data[index].KinhDo);
				$('#latitude').val(data[index].ViDo);
            }); 
			$("#rUpdate").attr("checked", "checked");
			setTimeout("$('#lbl_action').html('Cập nhật nhà trọ')",300);
			$('#btInsert').hide();
			$('#btUpdate').show();
        } //end success function
    });   //end ajax
}
function updateNhaTro(idNhaTro){
	// Xử lý nghiệp vụ 
	// Lấy dự liệu toàn bộ thông qua MaDuLieu ajax
	
	
	//alert('ok');
	// Chuyễn data lên form
	
	
	var strJSON = '';
		// Như vầy mới đúng
		alert($('#MaDuLieu').val());
		strJSON += '{"MaDuLieu":' + $('#MaDuLieu').val() +',';
		strJSON += '"MaTenDiaDiem":' + $('#MaTenDiaDiem').val() + ',';
		strJSON += '"MaDichVu":' + '20' + ',';
		strJSON += '"SoNha":' + '"' + $('#sonha').val() + '"' + ',';
		strJSON += '"ChuThich":' + '"' + $('#chuthich').val() + '"' + ','
		strJSON += '"MaDuong":'  + $('#mad').val() + ',';
		strJSON += '"MaPhuong":' + $('#maph').val() + ',';
		strJSON += '"MaQuanHuyen":' + $('#maqh').val() + ',';
		strJSON += '"MaTinhThanh":' + $('#matinhthanh').val() + ',';
		strJSON += '"KinhDo":' +  $('#longitude').val() + ',';
		strJSON += '"ViDo":' + $('#latitude').val() + '}';

		var objJSON = JSON.stringify(strJSON);
		alert(objJSON);
		$.ajax({
			url: "http://localhost:1445/NhaTroService.svc/Update",
			type: "PUT",
			contentType: "application/json; charset=utf-8",
			data: objJSON,
			success: function (msg) {
				alert('success');
			},
			error: function (msg) {
				alert(msg);
			}
		}); // end ajax 
}
function setMarker(item) {
    //alert(item);
    var latLng = new google.maps.LatLng(item.ViDo, item.KinhDo);
    var marker = new google.maps.Marker({
        position: latLng,
        map: map
    });
}
// Dùng cho chức năng tìm kiếm
function loadMarkerOption() {
    var lat, lng, zoom;
    initialize();
    $.ajax({
        url: urlQuery,
        data: "{}",
        type: "GET",
        contentType: "application/javascript", //set ajax call through cross domain
        dataType: "jsonp",
        success: function (data) {
            //loop the json array
            $.each(data, function (index) {
                if (index == 7) {
                    lat = data[index].ViDo;
                    lng = data[index].KinhDo;
                    str = lat + '-' + lng;
                    alert(str);
                }
                //set marker
                var latLng = new google.maps.LatLng(data[index].ViDo, data[index].KinhDo); //create latitude, longtitude
                var marker = new google.maps.Marker({ //set marker to map
                    position: latLng,
                    map: map
                }); //end set marker 
                //create marker event listener
                (function (marker) {
                    google.maps.event.addListener(marker, 'click', function () { //set click event

                        if (!infowindow) {
                            infowindow = new google.maps.InfoWindow();
                        }
                        //set content when I click this marker
                        infowindow.setContent(
                                'Số nhà: ' + data[index].SoNha + '<br>Chú thích : ' + data[index].ChuThich +
                                "<br /><span class=\"delete_address\" style=\"color:red;cursor:pointer\" onclick=\"deleteNhaTro(" + data[index].MaDuLieu + ")\">Xóa nhà trọ này</span><hr /><span class=\"delete_address\" style=\"color:red;cursor:pointer\" onclick=\"getNhaTroById(" + data[index].MaDuLieu + ")\">Cập nhật thông tin nhà trọ này</span>"
                            );

                        infowindow.open(map, marker);

                    });
                })(marker); //end create marker event listener

            }); //end each
        } //end success function
    });        //end ajax  
    zoom = 15;
   
    //loadMapAgain(lat, lng, zoom);

}
// Chưa sử dụng
function loadMapAgain(lat, lng, zoom) {
    var latlng = new google.maps.LatLng(lat, lng);
    var myOptions = {
        zoom: zoom,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map"), myOptions);
}
